package com.playwright.util.zhihu2toutiao;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.AriaRole;
import com.microsoft.playwright.options.LoadState;
import org.apache.commons.lang3.ObjectUtils;

import java.nio.file.Paths;
import java.util.List;

/**
 * @author liyanhao
 * @Date 2024-01-17 11:48
 */
public class ZhiHuUtils {




    private static String defaultPath = "C:\\auth\\ZhiHu_state.json";

    public static void main(String[] args) {

        try (Playwright playwright = Playwright.create()) {
            Page page = ZhiHuUtils.getPage(playwright);
            page.navigate("https://www.zhihu.com/hot");
            List<ElementHandle> similarElements = page.querySelectorAll(".HotItem-title");

            for (int i = 0; i < similarElements.size(); i++) {
                ElementHandle elementHandle = similarElements.get(i);
                String issue = elementHandle.textContent();
                //点击获取每个元素去通意千问获取答案
                System.out.println("------------------------------------------------");
                System.out.println(issue);  // 输出元素的文本内容
                String answer = YiYanUtils.getAnswer(issue);
                System.out.println("------------------------------------------------");
                System.out.println(answer);
                System.out.println("------------------------------------------------");
                elementHandle.click();
                answerZhihu(page,elementHandle,answer);
            }
        }
    }

    private static void answerZhihu(Page page,ElementHandle issue,String answer) {
        Page page1 = page.waitForPopup(() -> {
            issue.click();
        });
        page1.getByRole(AriaRole.MAIN).getByRole(AriaRole.BUTTON, new Locator.GetByRoleOptions().setName("​ 写回答")).click();
        page1.getByRole(AriaRole.TEXTBOX).locator("div").first().fill(answer);
        page1.getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("发布回答")).click();
    }

    public static void saveAuthZhiHu(String path) {
        if (ObjectUtils.isEmpty(path)) {
            path = defaultPath;
        }
        try (Playwright playwright = Playwright.create()) {

            Browser browser = PlaywrightUtils.getBrowser(playwright);

            BrowserContext context = browser.newContext();
            Page page = context.newPage();
            page.navigate("https://www.zhihu.com/");

            page.waitForLoadState(LoadState.DOMCONTENTLOADED); // 等待页面完全加载
            //等到热榜出现
            page.getByRole(AriaRole.MAIN).getByRole(AriaRole.LINK, new Locator.GetByRoleOptions().setName("热榜")).click();

            // 3. 保存认证后的浏览器状态
            String statePath = Paths.get("C:\\auth\\state.json").toString();
            BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
            options.setPath(Paths.get(statePath));
            context.storageState(options);

            context.close();
            browser.close();
        }
    }

    /**
     * 携带登录信息获取浏览器
     *
     * @param playwright
     * @return
     */
    public static BrowserContext getBrowserContext(Playwright playwright) {
        Browser browser = PlaywrightUtils.getBrowser(playwright);
        // 3. 保存认证后的浏览器状态
        String statePath = Paths.get("C:\\auth\\state.json").toString();
        BrowserContext.StorageStateOptions options = new BrowserContext.StorageStateOptions();
        options.setPath(Paths.get(statePath));
        // 加载之前保存的浏览器状态以保持登录状态
        BrowserContext context = browser.newContext(new Browser.NewContextOptions().setStorageStatePath(Paths.get(statePath)));
        return context;
    }

    public static Page getPage(Playwright playwright) {
        try {
            BrowserContext browserContext = getBrowserContext(playwright);
            Page page = browserContext.newPage();
            return page;
        } catch (Exception e) {
            System.out.println("未登录，登录一下");
            saveAuthZhiHu("");
            BrowserContext browserContext = getBrowserContext(playwright);
            Page page = browserContext.newPage();
            return page;
        }

    }


}
